package com.gxar.quick.ar.server.base.job;

import com.gxar.common.utils.CollectionUtils;
import com.gxar.quick.ar.server.base.common.enums.TransactionStatusEnum;
import com.gxar.quick.ar.server.base.common.enums.order.OrderStatusEnum;
import com.gxar.quick.ar.server.db.model.TransactionOrderEntity;
import com.gxar.quick.ar.server.db.service.OrderService;
import com.gxar.quick.ar.server.db.service.TransactionService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author nice
 * @version 1.0
 * @created 2023/12/5.
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class TransactionExpiredHandler {

    private final OrderService orderService;

    private final TransactionService transactionService;

    @XxlJob("transactionExpiredHandler")
    public void transactionExpiredHandler() {
        //找到过期的交易单
        List<TransactionOrderEntity> transactionOrderEntities = transactionService.queryExpiredTransaction(new Date());
        if (CollectionUtils.isEmpty(transactionOrderEntities)) {
            log.info("XXL-JOB, no transaction expired");
            return;
        }
        //更新订单状态
        List<Long> orderIds = transactionOrderEntities.stream().map(TransactionOrderEntity::getBusinessId)
                .collect(Collectors.toList());
        orderIds.stream().forEach(orderId -> orderService.updateOrderStatusById(orderId, OrderStatusEnum.CANCELLED));
        //更新交易单状态
        List<Long> transactionIds = transactionOrderEntities.stream().map(TransactionOrderEntity::getId)
                .collect(Collectors.toList());
        transactionIds.stream().forEach(orderId -> transactionService.updateTransactionStatusById(orderId,
                TransactionStatusEnum.TRANSACTION_CLOSE));
        log.info("XXL-JOB, transaction expired handler");
        XxlJobHelper.log("transaction expired execute success");
    }
}
